package com.itzhihao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzhihao.common.constant.ExistStatus;
import com.itzhihao.common.constant.OrderStatus;
import com.itzhihao.entity.Cart;
import com.itzhihao.entity.Order;
import com.itzhihao.entity.Product;
import com.itzhihao.entity.Store;
import com.itzhihao.entity.vo.OrderVo;
import com.itzhihao.mapper.OrderMapper;
import com.itzhihao.service.ICartService;
import com.itzhihao.service.IOrderService;
import com.itzhihao.service.IProductService;
import com.itzhihao.service.IStoreService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements IOrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private IProductService productService;
    @Resource
    private IStoreService storeService;
    @Resource
    private ICartService cartService;

    @Override
    public Order getDetail(Long id) {
        LambdaQueryWrapper<Order>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        queryWrapper.eq(Order::getId,id);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    public TableDataInfo selectListByStoreId(PageDomain pageDomain, Store store) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        Page<Order> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        queryWrapper
                .eq(Order::getStoreId,store.getId());
        queryWrapper.eq(Order::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        orderMapper.selectPage(page,queryWrapper);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getCurrent()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public TableDataInfo selectListByProductId(PageDomain pageDomain, Product product) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        Page<Order> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        queryWrapper
                .eq(Order::getProductId,product.getId());
        queryWrapper.eq(Order::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        orderMapper.selectPage(page,queryWrapper);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getCurrent()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public TableDataInfo getList(PageDomain pageDomain,Order order) {
        Long userId = SecurityUtils.getUserId();
        pageDomain.setPageStart((pageDomain.getPageNum()-1)*pageDomain.getPageSize());
//        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
//
//        queryWrapper
//                .lambda()
//                .eq(Order::getUserId,userId);
//        if (order.getStatus() != null){
//            queryWrapper.lambda().eq(Order::getStatus,order.getStatus());
//        }
//        queryWrapper.lambda().eq(Order::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
//        queryWrapper.lambda().orderByAsc(Order::getUpdateTime);
//        Page<Order> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
//        查询当前用户的订单列表
        List<OrderVo> list = orderMapper.getListByStatus(userId,pageDomain,order);
//        orderMapper.selectPage(page,queryWrapper);
        System.out.println(list.size());
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+list.size()+"条数据");
        tableDataInfo.setRows(list);
//        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public boolean deleteById(Long id) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Order::getIsDeleted, ExistStatus.NO_EXIST_STATUS.ordinal());
        updateWrapper.eq(Order::getId,id);
        int i = orderMapper.update(null, updateWrapper);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteByIds(List<Long> idLongList) {
        for (Long id:idLongList
        ) {
            boolean b = deleteById(id);
            if(!b){
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized boolean saveOrder(Order order) {
        Long userId = SecurityUtils.getUserId();
        Boolean isOwnStore = storeService.hasStore(userId, order.getStoreId());
        if(isOwnStore){
            return false;
        }
        if (order.getParams() != null && !order.getParams().isEmpty()) {
            Iterator<Map.Entry<String, Object>> entries = order.getParams().entrySet().iterator();
            while(entries.hasNext()){
                Map.Entry<String,Object> val = entries.next();
                String key = val.getKey();
                if(key.equals("cartId")){
                    Long id = (Long)val.getValue();
                    cartService.deleteById(id);
                }
            }
        }
        order.setUserId(userId);
        order.setCreateTime(DateUtils.getNowDate());
        order.setCreateBy(userId.toString());
        order.setUpdateTime(DateUtils.getNowDate());
        order.setStatus(OrderStatus.ORDERD.ordinal());
        int i = 0;
        order.setIsDeleted(ExistStatus.EXIST_STATUS.ordinal());
        order.setUpdateTime(DateUtils.getNowDate());
        Boolean isDel = productService.decreaseStock(order.getProductId(), order.getNum());
        if(!isDel){
            return false;
        }
        i = orderMapper.insert(order);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean updateStatus(Order order, int ordinal) {
        if((order.getStatus() == OrderStatus.ORDERD.ordinal() && ordinal == OrderStatus.SENDED.ordinal()) ||
            (order.getStatus() == OrderStatus.SENDED.ordinal() && ordinal == OrderStatus.ARRIVED.ordinal()) ||
            (order.getStatus() == OrderStatus.ARRIVED.ordinal() && ordinal == OrderStatus.GOT.ordinal()) ||
            (ordinal == OrderStatus.CANCEL.ordinal())){
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getId,order.getId())
                    .set(Order::getStatus,ordinal);
            int i = orderMapper.update(null, updateWrapper);
            if(i > 0){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}
